package com.starsea.book.ui.newpage

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.starsea.book.R
import com.starsea.book.base.VMBaseFragment
import com.starsea.book.databinding.FragmentHomeCategoryBinding
import com.starsea.book.ui.book.search.SearchActivity
import com.starsea.book.ui.main.MainFragmentInterface
import com.starsea.book.ui.newpage.adapter.MyPagerAdapter
import com.starsea.book.ui.newpage.viewmodel.HomeViewModel
import com.starsea.book.ui.newpage.weidget.tablayout.SlidingTabLayout
import com.starsea.book.utils.startActivity
import com.starsea.book.utils.viewbindingdelegate.viewBinding

/**
 * @author Lee
 * @createTime 2024-01-10 21 GMT+8
 * @desc :
 */
class CategoryFragment() : VMBaseFragment<HomeViewModel>(R.layout.fragment_home_category),
    MainFragmentInterface {

    private val binding by viewBinding(FragmentHomeCategoryBinding::bind)

    override val viewModel by activityViewModels<HomeViewModel>()

    val mFragments: MutableList<Fragment> = ArrayList()

    var myPagerAdapter: MyPagerAdapter? = null

    val listTitle: MutableList<String> = ArrayList()

    var index = 0

    constructor(position: Int) : this() {
        val bundle = Bundle()
        bundle.putInt("position", position)
        arguments = bundle
    }


    private val tabLayout: SlidingTabLayout by lazy {
        binding.titleBar.findViewById(R.id.tab_layout)
    }

    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
        setSupportToolbar(binding.titleBar.toolbar)

        listTitle.clear()
        mFragments.clear()
        listTitle.add("男生")
        listTitle.add("女生")
        mFragments.add(
            CategoryChildFragment.newInstance(1)
        )
        mFragments.add(
            CategoryChildFragment.newInstance(2)
        )

        if (myPagerAdapter == null)
            myPagerAdapter = MyPagerAdapter(childFragmentManager, mFragments, listTitle)

        binding.viewPagerBookshelf.offscreenPageLimit = listTitle.size
        binding.viewPagerBookshelf.adapter = myPagerAdapter
        tabLayout.setViewPager(binding.viewPagerBookshelf)
        binding.viewPagerBookshelf.currentItem = index
    }


    override fun onCompatCreateOptionsMenu(menu: Menu) {
        menuInflater.inflate(R.menu.home_category_title, menu)
    }

    override fun onCompatOptionsItemSelected(item: MenuItem) {
        super.onCompatOptionsItemSelected(item)
        when (item.itemId) {
            R.id.menu_search -> startActivity<SearchActivity>()
        }
    }

    override val position: Int? get() = arguments?.getInt("position")

}